﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
using Conusic;

namespace ConusicUI
{
    /// <summary>
    /// Description of ProfileSelector.
    /// </summary>
    public partial class ProfileSelector : UserControl, IFriendsListCommand, IGroupsListCommand, IGetProfileByUrlCommand
    {
        private Profile selectedProfile = null;
        private List<ListViewItem> savedList = new List<ListViewItem>();

        public Profile SelectedProfile
        {
            get { return this.selectedProfile; }
            private set
            {
                switch (value.ProfileType)
                {
                    case ProfileTypes.Profile:
                        this.linkLabel1.Text = String.Format("U: {0}, id:{1}", value.Name, value.Id);
                        break;
                    case ProfileTypes.Group:
                        this.linkLabel1.Text = String.Format("G: {0}, id:{1}", value.Name, value.Id);
                        break;
                    case ProfileTypes.Event:
                        this.linkLabel1.Text = String.Format("E: {0}, id:{1}", value.Name, value.Id);
                        break;
                    case ProfileTypes.PublicPage:
                        this.linkLabel1.Text = String.Format("PP: {0}, id:{1}", value.Name, value.Id);
                        break;
                }
                this.selectedProfile = value;
            }
        }

        public ProfileSelector()
        {
            InitializeComponent();
        }

        void IFriendsListCommand.Execute(List<Friend> friends)
        {
            this.Invoke((MethodInvoker)delegate
                                            {
                                                UpdateFriends(friends);
                                                SetEnabled(true);
                                            });
        }


        private void ListView1SelectedIndexChanged(object sender, EventArgs e)
        {
            var listview = (ListView)sender;

            if (listview.SelectedItems.Count != 0)
            {
                if (listview.SelectedItems[0].Tag is Friend)
                {
                    this.SelectedProfile = (Profile)((Friend)listview.SelectedItems[0].Tag);
                }
                else
                {
                    this.SelectedProfile = (Profile)((Group)listview.SelectedItems[0].Tag);
                }
            }
        }

        private void NavigateToSelectedProfile(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (SelectedProfile != null && !String.IsNullOrEmpty(SelectedProfile.FullUrl))
            {
                System.Diagnostics.Process.Start(SelectedProfile.FullUrl);
            }
        }

        private void TextBoxSearchProfile(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                RequestProfileById(textBoxSearchProfile.Text);
            }
        }

        private void Button1Click(object sender, EventArgs e)
        {
            RequestProfileById(textBoxSearchProfile.Text);
        }

        private void UpdateList(object sender, EventArgs e)
        {
            this.labelHelpUse.Hide();
            this.ActiveControl = textBoxQS;
            textBoxQS.SelectAll();
            if (this.radioButtonFriends.Checked)
            {
                SetEnabled(false);
                VkontakteFriends.UpdateFriendsAsync(this);
            }
            else if (this.radioButtonGroups.Checked)
            {
                SetEnabled(false);
                VkontakteGroups.UpdateGroupsAsync(this);
            }
        }

        private void SetEnabled(bool enabled)
        {
            radioButtonFriends.Enabled = enabled;
            radioButtonGroups.Enabled = enabled;
            listViewProfiles.Enabled = enabled;
        }

        private void RequestProfileById(string url)
        {
            int k = 0;
            if (int.TryParse(url, out k))
            {
                Profile.GetProfileByUrlAsync("id" + url, this);
            }
            else
            {
                Profile.GetProfileByUrlAsync(url, this);
            }
        }

        void IGetProfileByUrlCommand.Execute(Profile profile)
        {
            this.Invoke((MethodInvoker)delegate { SelectedProfile = profile; });
        }

        void IGetProfileByUrlCommand.Fail(Exception exc)
        {
            this.Invoke((MethodInvoker)delegate { GetProfileByUrlCommandFail(exc); });
        }

        private void GetProfileByUrlCommandFail(Exception exc)
        {
            if (exc is WebException)
            {
                ErrorReport.ShowPopup("Страница не найдена. Проверьте, не ошиблись ли вы в наборе.",
                                      this.textBoxSearchProfile);
            }
            else
            {
                ErrorReport.Show(exc, this.textBoxSearchProfile);
            }
        }

        void IGroupsListCommand.Execute(List<Group> group)
        {
            this.Invoke((MethodInvoker)delegate
                                            {
                                                UpdateGroups(group);
                                                SetEnabled(true);
                                            });
        }

        void IGroupsListCommand.Fail(Exception exc)
        {
            this.Invoke((MethodInvoker)delegate
                                            {
                                                ErrorReport.Show(exc, this);
                                                SetEnabled(true);
                                            });
        }


        private void UpdateFriends(List<Friend> friends)
        {
            listViewProfiles.Clear();
            savedList.Clear();
            savedList.Capacity = friends.Count;
            foreach (var elem in friends)
            {
                ListViewItem item = new ListViewItem(elem.Name);
                item.Tag = elem;

                savedList.Add(item);
                listViewProfiles.Items.Add(item);
            }

        }

        private void UpdateGroups(List<Group> group)
        {
            listViewProfiles.Clear();
            savedList.Clear();
            savedList.Capacity = group.Count;

            foreach (var elem in group)
            {
                var item = new ListViewItem(elem.Name);
                item.Tag = elem;

                savedList.Add(item);
                listViewProfiles.Items.Add(item);
            }

        }

        private void TextBoxQsTextChanged(object sender, EventArgs e)
        {
            listViewProfiles.SuspendLayout();
            listViewProfiles.ListViewItemSorter = null;
            listViewProfiles.Items.Clear();
            string text = textBoxQS.Text.ToLowerInvariant();

            foreach (var item in savedList)
            {
                if (item.Text.ToLowerInvariant().Contains(text))
                {
                    listViewProfiles.Items.Add(item);
                }
            }

            listViewProfiles.ResumeLayout();

            if (listViewProfiles.Items.Count == 1)
            {
                listViewProfiles.Items[0].Selected = true;
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}